﻿//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Expenses.ViewModels;
using Expenses.ExpenseService;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Media.Imaging;
using Windows.System.UserProfile;
using System.ServiceModel;
using Windows.UI.Notifications;
using Windows.Data.Xml.Dom;
using Windows.ApplicationModel.DataTransfer;
using Windows.UI;
using Windows.UI.Text;

namespace Expenses.Views
{
    public sealed partial class MainPage : Expenses.Common.LayoutAwarePage
    {
        SummaryItemsViewModel summaryItemsViewModel = null;
        ObservableCollection<SummaryItemViewModel> summaryItems = null;
        ExpenseReportsViewModel expenseReportsViewModel = null;
        bool loadingSummaryItems = true;
        decimal amountOwedToCreditCard = 0M;
        decimal amountOwedToEmployee = 0M;
        string currentUserName = string.Empty;
        private DataTransferManager dataTransferManager = null;
        public Windows.ApplicationModel.Activation.LaunchActivatedEventArgs LaunchArgs;

        public MainPage()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            loadingSummaryItems = true;

            currentUserName = App.UserName;
            UserNameTextBlock.Text = currentUserName;
            
            GetData();

            // Register handler for DataRequested events for sharing
            dataTransferManager = DataTransferManager.GetForCurrentView();
            dataTransferManager.DataRequested += new TypedEventHandler<
                DataTransferManager, DataRequestedEventArgs>(OnDataRequested);
        }

        private async void GetData()
        {
            MainPageProgressRing.IsActive = true;

            summaryItemsViewModel = new SummaryItemsViewModel();
            summaryItems = await summaryItemsViewModel.GetSummaryItems();
            SummaryItemsViewSource.Source = summaryItemsViewModel.SummaryItems;
            GroupedSummaryItemsViewSource.Source = summaryItemsViewModel.GroupedSummaryItems;

            expenseReportsViewModel = new ExpenseReportsViewModel();
            amountOwedToCreditCard = await 
                expenseReportsViewModel.GetAmountOwedToCreditCard(
                App.EmployeeId);
            amountOwedToEmployee = await
                expenseReportsViewModel.GetAmountOwedToEmployee(
                App.EmployeeId);

            // Update the tile with information
            XmlDocument tileXml = TileUpdateManager.GetTemplateContent(
                TileTemplateType.TileWideText03);
            XmlNodeList tileTextAttributes = tileXml.GetElementsByTagName("text");
            foreach (var tileTextAttr in tileTextAttributes)
            {
                tileTextAttr.InnerText = string.Format("{0} charge(s) for {1:C}",
                    summaryItemsViewModel.NumberOfCharges, summaryItemsViewModel.AmountOfCharges);
            }
            var tileNotification = new TileNotification(tileXml);
            TileUpdateManager.CreateTileUpdaterForApplication().Update(
                tileNotification);

            loadingSummaryItems = false;

            if (summaryItems.Count() == 0)
            {
                NoDataTextBlock.Visibility = Visibility.Visible;
            }
            MainPageProgressRing.IsActive = false;
        }

        private void NewReportButton_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(ExpenseReportPage), null);
        }

        private void SummaryItemsGridView_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (!loadingSummaryItems)
            {
                string groupName = ((GroupInfoList<object>)e.ClickedItem).Key.ToString();
                switch (groupName)
                {
                    case "Charges":
                        this.Frame.Navigate(typeof(ChargesPage));
                        break;
                    case "Saved Reports":
                        this.Frame.Navigate(typeof(ExpenseReportsPage), "Saved Reports");
                        break;
                    case "Pending Reports":
                        this.Frame.Navigate(typeof(ExpenseReportsPage), "Pending Reports");
                        break;
                    case "Needing Approval":
                        this.Frame.Navigate(typeof(ExpenseReportsPage), "Needing Approval");
                        break;
                    case "Past Reports":
                        this.Frame.Navigate(typeof(ExpenseReportsHistoryPage));
                        break;
                    default:
                        break;
                }
            }
        }

        private void Charge_Tapped(object sender, TappedRoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(ExpenseReportPage));
        }

        private void PastReportsButton_Tapped(object sender, TappedRoutedEventArgs e)
        {
            if (!loadingSummaryItems)
            {
                this.Frame.Navigate(typeof(ExpenseReportsHistoryPage));
            }
        }

        private void ReportsButton_Tapped(object sender, TappedRoutedEventArgs e)
        {

        }

        private void MainPage_GotFocus(object sender, RoutedEventArgs e)
        {
            if (currentUserName != App.UserName)
            {
                currentUserName = App.UserName;
                loadingSummaryItems = true;
                GetData();
                UserNameTextBlock.Text = currentUserName;
            }
        }

        void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            var request = args.Request;
            request.FailWithDisplayText("This page does not support sharing.");
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            dataTransferManager.DataRequested -= new TypedEventHandler<
                DataTransferManager, DataRequestedEventArgs>(OnDataRequested);
        }

    }
}
